from wormbane.engine.actions.dig import action_dig
from wormbane.engine.actions.hit import action_hit
from wormbane.engine.actions.push import action_push
from wormbane.geometry import direction_to_vector, is_diagonal_direction
from wormbane.model.feature import Door, Doorway, Wall, Corridor, Floor
from wormbane.util.format import format_count, to_definite_article
from wormbane.util.random_ import percent_chance

import random

def command_move(dir, game):
    dest = game.level.cells.get(game.hero.pos + direction_to_vector(dir))
    if not dest:
        game.write(game.hero, 'cannot go that way')
        return
    if not dest.passable:
        if dest.monster:
            action_hit(game.hero, dest.monster, game)
            game.hero_moved = True
            return
        if dest.feature.passable and dest.boulder:
            if game.hero.pick:
                action_dig(game.hero, dest.boulder, game)
                game.hero_moved = True
                return
            else:
                action_push(game.hero, dest.boulder, game)
                game.hero_moved = True
                return
        if dest.feature.is_wall:
            if game.hero.pick:
                action_dig(game.hero, dest.feature, game)
                game.hero_moved = True
                return
            else:
                game.write(game.hero, 'bumps into', dest.feature)
                game.hero_moved = True
                return
        elif dest.feature.is_door:
            if dest.feature.material == 'stone' and game.hero.pick:
                action_dig(game.hero, dest.feature, game)
                game.hero_moved = True
            else:
                game.write(game.hero, 'kicks', dest.feature)
                if dest.feature.material == 'wood':
                    if percent_chance(50):
                        game.write(dest.feature, 'splinters')
                        Doorway(axis = dest.feature.axis,
                                material = dest.feature.material).move_to(dest)
                else:
                    game.write('Ouch!')
                game.hero_moved = True
        else:
            game.write(game.hero, 'cannot go that way')
        return
    if (is_diagonal_direction(dir)
        and (game.hero.env.feature.is_door or dest.feature.is_door)):
        game.write(game.hero, 'cannot pass that way')
        return
    game.hero.move_to(dest)
    game.hero_moved = True

    if dest.feature.kind not in ('corridor', 'floor'):
        game.write('There is %s here.' % dest.feature)
    if dest.top_item:
        items = dest.items
        if len(items) == 1:
            game.write('There %s %s here.'
                       % ('are' if items[0].plural else 'is', items[0]))
        else:
            game.write('There are items here.')
